/**
 * Spark创作主界面组件
 * 包含火花输入、对话引导、大纲编辑和内容生成的完整流程
 */

import React, { useState } from 'react'
import { Card, Button, Progress, Alert, Space } from 'antd'
import { FireOutlined, BookOutlined, EditOutlined } from '@ant-design/icons'
import { useSparkCreation, useSparkCreationProgress } from '../../state/spark'
import SparkInput from './SparkInput'
import DialogInterface from './DialogInterface'
import OutlineEditor from './OutlineEditor'
import ContentGenerator from './ContentGenerator'
import './SparkCreationPanel.css'

export interface SparkCreationPanelProps {
  onArticleGenerated?: (content: string) => void
}

const SparkCreationPanel: React.FC<SparkCreationPanelProps> = ({
  onArticleGenerated
}) => {
  const { state, actions } = useSparkCreation()
  const { progress, currentStep, totalSections, completedSections } = useSparkCreationProgress()
  
  const [activeTab, setActiveTab] = useState<'input' | 'dialog' | 'outline' | 'generate'>('input')

  // 处理火花输入提交
  const handleSparkSubmit = async (sparkInput: string) => {
    await actions.startSpark(sparkInput)
    setActiveTab('dialog')
  }

  // 处理对话完成
  const handleDialogComplete = () => {
    setActiveTab('outline')
  }

  // 处理大纲生成完成
  const handleOutlineGenerated = () => {
    setActiveTab('generate')
  }

  // 处理内容生成完成
  const handleContentGenerated = (content: string) => {
    onArticleGenerated?.(content)
  }

  // 渲染进度条
  const renderProgress = () => {
    if (!state.currentSession && !state.isLoading) {
      return null
    }

    return (
      <div className="spark-progress">
        <Progress
          percent={progress}
          status={state.error ? 'exception' : state.isGenerating ? 'active' : 'normal'}
          format={(percent) => `${percent}%`}
        />
        <div className="spark-progress-info">
          <span className="current-step">{currentStep}</span>
          {totalSections > 0 && (
            <span className="section-progress">
              {completedSections}/{totalSections} 段落已完成
            </span>
          )}
        </div>
      </div>
    )
  }

  // 渲染错误信息
  const renderError = () => {
    if (!state.error) return null

    return (
      <Alert
        message="创作过程中出现错误"
        description={state.error.message}
        type="error"
        closable
        onClose={actions.clearError}
        style={{ marginBottom: 16 }}
        action={
          <Button size="small" onClick={actions.clearError}>
            重试
          </Button>
        }
      />
    )
  }

  // 渲染主要内容
  const renderContent = () => {
    // 显示火花输入界面
    if (activeTab === 'input' || !state.currentSession) {
      return (
        <SparkInput
          onSparkSubmit={handleSparkSubmit}
          isLoading={state.isLoading}
        />
      )
    }

    // 显示对话引导界面
    if (activeTab === 'dialog' && state.currentDialogStep) {
      return (
        <DialogInterface
          dialogStep={state.currentDialogStep}
          dialogState={state.currentSession.dialogState}
          onUserResponse={actions.continueDialog}
          onComplete={handleDialogComplete}
          isLoading={state.isLoading}
        />
      )
    }

    // 显示大纲编辑界面
    if (activeTab === 'outline' || (state.currentOutline && !state.currentDialogStep)) {
      return (
        <OutlineEditor
          outline={state.currentOutline}
          onOutlineChange={actions.updateOutline}
          onSectionUpdate={actions.updateSection}
          onGenerateContent={actions.generateSectionContent}
          onComplete={handleOutlineGenerated}
          isLoading={state.isLoading}
        />
      )
    }

    // 显示内容生成界面
    if (activeTab === 'generate' && state.currentOutline) {
      return (
        <ContentGenerator
          outline={state.currentOutline}
          generationState={state.generationState}
          onGenerateSection={actions.generateSectionContent}
          onRegenerateSection={actions.regenerateSectionContent}
          onGenerateAll={actions.generateFullArticle}
          onContentGenerated={handleContentGenerated}
          isGenerating={state.isGenerating}
        />
      )
    }

    return null
  }

  // 渲染导航标签
  const renderTabs = () => {
    if (!state.currentSession) return null

    const tabs = [
      { key: 'input', label: '火花输入', icon: <FireOutlined /> },
      { key: 'dialog', label: '对话引导', icon: <BookOutlined />, disabled: !state.currentSession },
      { key: 'outline', label: '大纲编辑', icon: <EditOutlined />, disabled: !state.currentOutline },
      { key: 'generate', label: '内容生成', icon: <EditOutlined />, disabled: !state.currentOutline }
    ]

    return (
      <div className="spark-tabs">
        {tabs.map(tab => (
          <Button
            key={tab.key}
            type={activeTab === tab.key ? 'primary' : 'default'}
            icon={tab.icon}
            disabled={tab.disabled}
            onClick={() => setActiveTab(tab.key as any)}
            size="small"
          >
            {tab.label}
          </Button>
        ))}
      </div>
    )
  }

  return (
    <div className="spark-creation-panel">
      <Card
        className="spark-panel-card"
        bodyStyle={{ padding: '16px' }}
        bordered={false}
      >
        {renderError()}
        {renderProgress()}
        {renderTabs()}
        
        <div className="spark-content">
          {renderContent()}
        </div>

        {/* 底部操作栏 */}
        <div className="spark-actions">
          <Space>
            {state.currentSession && (
              <Button onClick={actions.resetDialog}>
                重新开始
              </Button>
            )}
            
            {state.currentSession && (
              <Button onClick={actions.saveSession}>
                保存会话
              </Button>
            )}
            
            {state.currentOutline && progress === 100 && (
              <Button 
                type="primary"
                onClick={() => {
                  const content = state.currentSession?.finalContent || ''
                  actions.exportToEditor(content)
                }}
              >
                导入编辑器
              </Button>
            )}
          </Space>
        </div>
      </Card>
    </div>
  )
}

export default SparkCreationPanel